import java.util.Scanner;

public class project3 {

    // 假设这里是你原有的排序方法，我们使用它
    public static void quickSort(int[] arr, int[] values, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, values, low, high);
            quickSort(arr, values, low, pivotIndex - 1);
            quickSort(arr, values, pivotIndex + 1, high);
        }
    }
    private static int partition(int[] arr, int[] values, int low, int high) {
        int pivot = arr[high];  // 使用重量作为基准值
        int pivotValue = values[high];
        int i = low - 1;
        for (int j = low; j < high; j++) {
            // 如果当前物品的重量小于等于基准，交换
            if (arr[j] <= pivot) {
                i++;
                swap(arr, values, i, j);
            }
        }
        swap(arr, values, i + 1, high);
        return i + 1;
    }

    private static void swap(int[] arr, int[] values, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        temp = values[i];
        values[i] = values[j];
        values[j] = temp;
    }

    // 贪心算法解背包问题
    public static double fractionalKnapsack(int capacity, int[] weights, int[] values) {
        int n = weights.length;
        // 计算每个物品的单位价值
        double[] valuePerWeight = new double[n];
        for (int i = 0; i < n; i++) {
            valuePerWeight[i] = (double) values[i] / weights[i];
        }

        // 使用排序后的物品（例如按重量排序）
        quickSort(weights, values, 0, n - 1);

        double totalValue = 0.0;
        for (int i = 0; i < n && capacity > 0; i++) {
            // 如果当前物品的重量小于背包剩余容量，完全放入
            if (weights[i] <= capacity) {
                totalValue += values[i];
                capacity -= weights[i];
            } else {
                // 否则，放入物品的部分
                totalValue += valuePerWeight[i] * capacity;
                capacity = 0;
            }
        }
        return totalValue;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 输入背包的容量
        System.out.print("请输入背包的容量: ");
        int capacity = scanner.nextInt();

        // 输入物品的数量
        System.out.print("请输入物品的数量: ");
        int n = scanner.nextInt();

        int[] weights = new int[n];
        int[] values = new int[n];

        // 输入每个物品的重量和价值
        System.out.println("请输入物品的重量和价值: ");
        for (int i = 0; i < n; i++) {
            weights[i] = scanner.nextInt();
            values[i] = scanner.nextInt();
        }

        // 求解可分背包问题
        double maxValue = fractionalKnapsack(capacity, weights, values);

        // 输出最大价值
        System.out.println("背包能容纳的最大价值是: " + maxValue);

        scanner.close();
    }
}
